<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>图像识别管理系统</title>
    <link href="../css/common.css" rel="stylesheet">
    <link rel="stylesheet" href="../css/layui.css" media="all">
    <link id="layuicss-layer" rel="stylesheet" href="../css/modules/layer/default/layer.css" media="all">
    <script src="../js/jquery-1.12.4.js"></script>
    <script type="text/javascript" src="../js/jstime/laydate.js"></script>
    <script type="text/javascript" src="../js/layui.js" charset="utf-8"></script>
    <script type="text/javascript" src="../js/common.js" charset="utf-8"></script>
    <style>
        .layui-table img {
            width: 100px;height: 100px;
        }
    </style>
</head>
<script>

</script>

<body>

<div class="demo-transfer" id="test7"></div>
<div class="searchBar">
    <label>用户账号：</label><input id="username" style="width:80px;" />
    <label>用户昵称：</label><input id="nickname" style="width:80px;" />
    <label>创建日期从：</label><input autocomplete="off" class="laydate-icon" id="createdTimeStart" />
    <label>到：</label><input autocomplete="off" class="laydate-icon" id="createdTimeEnd" />
    <button id="search" data-type="check">查询</button>
</div>

<script type="text/html" id="toolbar">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm" lay-event="refresh">刷新</button>
        <button id="addSysInfo" class="layui-btn layui-btn-sm" lay-event="addSysInfo">新增</button>
        <button id="modifySysInfo" class="layui-btn layui-btn-sm" lay-event="modifySysInfo">修改</button>
        <button id="remove" class="layui-btn layui-btn-sm" lay-event="remove">删除</button>
    </div>
</script>

<table id="tableList" lay-filter="tableList"></table>

</body>

</html>

<script type="text/javascript">
    layui.config({base:'../js/lay/modules/'}).extend({tableSelect:'tableSelect'}).use(["table", "layer", "upload", "element",'tableSelect','form','upload'], function () {
    // layui.use(["table", "layer", "upload", "element", 'transfer', 'util'], function () {
        let table = layui.table,element = layui.element,$ = layui.jquery,form = layui.form,upload = layui.upload,tableSelect = layui.tableSelect,tree = layui.tree,treeSelect = layui.treeSelect;
        // var table = layui.table;
        // var upload = layui.upload;
        // var element = layui.element;
        var AddLoad = null;//添加弹窗
        var ModifyLoad = null;//修改弹窗
        var yesIndex = null;//(弹出层)yes按钮
        var imageUrl = null;
        //初始化表格
        function init() {
            var sH = layui.$(".searchBar").height();
            sH += 45;
            sH = 'full-' + sH;
            table.render({
                elem: '#tableList'
                , toolbar: '#toolbar',
                defaultToolbar: [{ title: '汇总', layEvent: 'collect', icon: 'layui-icon-tips' },'filter', 'print']
                , height: 'full-100'
                , method: "post"
                // ,contentType: "application/json;charset=utf-8"
                , request: {
                    pageName: "page", // 页码的参数名称，默认：page
                    limitName: "rows" // 每页数据量的参数名，默认：limit
                }
                ,headers: { token: localStorage.getItem("token") }
                , parseData: function (res) {//将回调函数解析成table所规定的数据格式
                    return {
                        msg: res.errMsg,
                        count: res.data ? res.data.total : 0,
                        data: res.data ? res.data.rows : [],
                        code: res.errCode
                    };
                }
                , limit: 50
                , limits: [10,50, 100, 500, 1000, 2000]
                , url: webUrl + '/userinfo/getPage' //数据接口
                , page: true //开启分页
                , cols: [[ //表头
                    { type: 'checkbox', fixed: 'left',style:'height:48px;width:48px;line-height:48px!important;' },
                    { field: 'userId',hide:true, sort: true, title: '用户ID',width:'10%' }
                    , { field: 'username', sort: true, title: '用户账号' ,width:'20%'}
                    , { field: 'nickname', sort: true, title: '用户昵称' ,width:'20%' }
                    , { field: 'headImageUrl', sort: true, title: '头像',width:'20%',templet:'<div><img src="{{d.headImageUrl}}"></div>',style:'height:10px;width:10px;line-height:48px!important;' }
                    , { field: 'createdBy', sort: true, title: '创建人ID',width:'10%' }
                    , { field: 'createdTime', sort: true, title: '创建时间',width:'10%' }
                     , { field: 'updatedBy', sort: true, title: '更新人ID',width:'10%' }
                    , { field: 'updatedTime', sort: true, title: '更新时间',width:'10%' }
                ]],
                where: {
                    token: getCookie("token")
                },
                done: function (res) {
                    if (res.code == "000001") {
                        layer.confirm('登录信息已过期，请重新登录', { title: '系统提示', btn: ['确认'] }, function (index) {
                            layer.close(index);
                            window.parent.returnLogin();
                        });
                    }
                }
            });
        }
        init();
        //搜索
        function search(page) {
            //执行重载
            var query = page ? { page: { curr: page } } : {}
            query['where'] = {
                username: layui.$("#username").val(),
                nickname: layui.$("#nickname").val(),
                createdTimeStart: layui.$("#createdTimeStart").val(),
                createdTimeEnd: layui.$("#createdTimeEnd").val(),
            }
            table.reload('tableList', query);
        }

        //监听工具条事件
        table.on('toolbar(tableList)', function (obj) {
            // var tableList = layui.table.cache["tableList"];
            var checkStatus = table.checkStatus(obj.config.id);
            var data = checkStatus.data;
            switch (obj.event) {
                case 'addSysInfo' :
                    openAddLevel();
                    break;
                case 'modifySysInfo' :
                    if (data.length > 1) {
                        layer.msg('只能修改单条数据');
                        return;
                    }
                    if (data.length < 1) {
                        layer.msg('未选中任何数据');
                        return;
                    }
                    openModifyLevel(data);
                    break;
                case 'remove' :
                    if (data.length <= 0) {
                        layer.msg('未选中任何数据');
                        return;
                    }
                    deleteLevel(data);

                    break;
                case 'collect':


                    break;
                case 'refresh':
                    search();
                    break;
            };
        })

        $('#search').on('click', function () {
            search(1);
        });


    //打开添加信息弹窗
    function openAddLevel() {
        layer.open({
            type: 1,
            title: "添加",
            area: "600px",
            shade: 0.5,
            btn: ["确认", "取消"],
            offset: '100px',
            btnAlign: "c",
            moveType: 1,
            content:
                '<div class="popupCont">' +
                '<label  class="w60"><b class="mustLabel">*</b>用户账号:</label><input id="new_username" autocomplete="off"  style="width:120px;"/>' +
                '<label  class="w60"><b class="mustLabel">*</b>用户昵称:</label><input id="new_nickname" autocomplete="off"  style="width:120px;"/>' +
                '</div>' +
                '<div class="popupCont">' +
                '<label  class="w60"><b class="mustLabel">*</b>用户密码:</label><input id="new_password"  lay-verify="required/pass" autocomplete="off"  style="width:120px;"/>' +
                '<label  class="w60" ><b class="mustLabel">*</b>确认密码:</label><input id="new_password2"  lay-verify="required/pass" autocomplete="off"  style="width:120px;" />' +
                '</div>' +
                '<div class="popupCont">' +
                '<label  class="w60"><b class="mustLabel">*</b>邮箱:</label><input id="new_email" autocomplete="off"  style="width:120px;"/>' +
                '</div>' +
                '<div class="layui-upload" style="margin-left: 110px;margin-bottom: 30px;">' +
                '            <button type="button" class="layui-btn" id="uploadImg">上传头像</button>' +
                '            <div style="display:none;">' +
                '                <input type="text" name="img_url" id="ipt_fileName" autocomplete="off" class="layui-input">' +
                '            </div>' +
                '            <div class="layui-upload-list">' +
                '                <img class="layui-upload-img" style="width:100px;height:100px;"  id="img_id">' +
                '                <p id="demoText"></p>' +
                '            </div>' +
                '            <div style="width: 95px;">' +
                '                <div class="layui-progress layui-progress-big" lay-showpercent="yes" lay-filter="upload_filter">' +
                '                    <div class="layui-progress-bar" lay-percent=""></div>' +
                '                </div>' +
                '            </div>' +
                '        </div>'
            , success: function () {
                uploadImage();
                imageUrl=null;
            }
            , yes:(index)=>{
            confirmInfoMsg("add");
            yesIndex = index;
        },
        });
    }


    //打开修信息弹窗
    function openModifyLevel(data) {
        /* 		console.log(data); */
        layer.open({
            type: 1,
            title: "修改信息",
            area: "600px",
            shade: 0.5,
            btn: ["确认", "取消"],
            offset: '100px',
            btnAlign: "c",
            moveType: 1,
            content:
                '<div class="popupCont">' +
                '<label  class="w60" >用户账号:</label><input id="new_username" autocomplete="off"  style="width:120px;"/>' +
                '<label  class="w60" >用户昵称:</label><input id="new_nickname" autocomplete="off"  style="width:120px;"/>' +
                '</div>' +
                '<div class="layui-upload" style="margin-left: 110px;margin-bottom: 30px;">' +
                '            <button type="button" class="layui-btn" id="uploadImg">上传头像</button>' +
                '            <div style="display:none;">' +
                '                <input type="text" name="img_url" id="ipt_fileName" autocomplete="off" class="layui-input">' +
                '            </div>' +
                '            <div class="layui-upload-list">' +
                '                <img class="layui-upload-img" style="width:100px;height:100px;" id="img_id">' +
                '                <p id="demoText"></p>' +
                '            </div>' +
                '            <div style="width: 95px;">' +
                '                <div class="layui-progress layui-progress-big" lay-showpercent="yes" lay-filter="upload_filter">' +
                '                    <div class="layui-progress-bar" lay-percent=""></div>' +
                '                </div>' +
                '            </div>' +
                '        </div>' +
                '<div class="popupCont">' +
                '<input type="hidden" id="userId" />' +
                '</div>'
            , success: function () {
                uploadImage();
                data = data[0];
                $("#userId").val(data.userId);
                $("#new_username").val(data.username);
                $("#new_nickname").val(data.nickname);
                $('#img_id').attr('src', data.headImageUrl); //图片
            }
            , yes:(index)=>{
            confirmInfoMsg("modify");
            yesIndex = index;
        },
        });
    }

    //校验输入信息
    function confirmInfoMsg(flag) {


        var new_username = $("#new_username").val();
        var new_nickname = $("#new_nickname").val();
        var new_password = $("#new_password").val();
        var new_password2 = $("#new_password2").val();
        var email = $("#new_email").val();
        if (flag == "modify") {
            var userId = $("#userId").val();
        }
        if(/(^\_)|(\__)|(\_+$)/.test(new_username)){
            layer.msg("用户名首尾不能出现下划线\'_\'");
            return;
        }
        // if(/^\d+\d+\d$/.test(new_username)){
        //     layer.msg("用户名不能全为数字\'_\'");
        //     return;
        // }
        new_username = $.trim(new_username);
        new_nickname = $.trim(new_nickname);
        if(flag === "add") {

            if ($('#new_password').val() !== $('#new_password2').val())
            {
                layer.msg("两次密码输入不一致！");
                return;
            }

            if (new_username === "") {
                layer.msg("账号不能为空");
                return;
            }
            if (new_nickname === "") {
                layer.msg("昵称不能为空");
                return;
            }
            if (new_password === "") {
                layer.msg("密码不能为空");
                return;
            }
            if (imageUrl === "" || imageUrl === null) {
                layer.msg("请上传头像");
                return;
            }

        }
        if (flag == "add") {
            var data = {
                /* type:newType, */
                username: new_username,
                nickname: new_nickname,
                password: new_password,
                headImageUrl: imageUrl,
                email:email
            };
            //添加的操作
            requestAdd(data);
        } else {
            //修改的操作
            var data = {
                userId: userId,
                username: new_username,
                nickname: new_nickname,
                headImageUrl: imageUrl,
            };
            requestModify(data);
        }
    }

    //添加订单的请求
    function requestAdd(data) {
        console.log(data);
        AddLoad = layer.load(2, { shade: 0.1 })
        sendPostAjax(
            webUrl + "/userinfo/saveUser",
            data,
            AddOrderCallBack
        );
    }

    //添加订单的回调
    function AddOrderCallBack(data) {
        layer.close(AddLoad);
        /* console.log(data); */
        if (data == null) {
            return;
        }
        if (data.errCode == "000001") {
            layer.confirm('登录信息已过期，请重新登录', { title: '系统提示', btn: ['确认'] }, function (index) {
                layer.close(index);
                window.parent.returnLogin();
            });
            return;
        }
        if (data.errCode == "000000") {
            layer.close(yesIndex);
            layer.msg(data.errMsg);
        } else {
            layer.alert(data.errMsg);
            return;
        }
        search(1);
    }


    //修改订单的请求
    function requestModify(data) {
        /* 	console.log(data); */
        ModifyLoad = layer.load(2, { shade: 0.1 })
        sendPostAjax(
            webUrl + "/userinfo/modify",
            data,
            ModifyOrderCallBack
        );
    }

    //修改订单的回调
    function ModifyOrderCallBack(data) {
        layer.close(ModifyLoad);
        /* console.log(data); */
        if (data == null) {
            return;
        }
        if (data.errCode == "000001") {
            layer.confirm('登录信息已过期，请重新登录', { title: '系统提示', btn: ['确认'] }, function (index) {
                layer.close(yesIndex);
                window.parent.returnLogin();
            });
            return;
        }
        if (data.errCode == "000000") {
            layer.close(yesIndex);
            layer.msg(data.errMsg);
        } else {
            layer.alert(data.errMsg);
            return;
        }
        search(1);
    }
    //删除订单请求
    function deleteLevel(data) {
        var idList = '';
        for (var i = 0; i < data.length; i++) {
            if (i == data.length - 1) {
                idList += data[i].userId;
            } else {
                idList += data[i].userId + ",";
            }
        }
        var data = {
            idList: idList
        }
        DeleteLoad = layer.load(2, { shade: 0.1 })
        sendPostAjax(
            webUrl + "/userinfo/remove",
            data,
            deleteOrderCallBack
        );
    }
    //删除订单回调
    function deleteOrderCallBack(data) {
        layer.close(DeleteLoad);
        /* console.log(data); */
        if (data == null) {
            return;
        }
        if (data.errCode == "000001") {
            layer.confirm('登录信息已过期，请重新登录', { title: '系统提示', btn: ['确认'] }, function (index) {
                layer.close(index);
                window.parent.returnLogin();
            });
            return;
        }
        if (data.errCode == "000000") {
            layer.msg(data.errMsg);
        } else {
            layer.alert(data.errMsg);
            return;
        }
        search(1);
    }

        function outDate() {
            var createdTimeStart = {
                elem: '#createdTimeStart',
                format: 'YYYY-MM-DD',
                max: '2099-12-31',
                choose: function (datas) {
                }
            };
            $("#createdTimeStart").click(function () {
                laydate(createdTimeStart);
                createdTimeStart.start = laydate.now();
            })
            var createdTimeEnd = {
                elem: '#createdTimeEnd',
                format: 'YYYY-MM-DD',
                max: '2099-12-31',
                choose: function (datas) {
                }
            };
            $("#createdTimeEnd").click(function () {
                laydate(createdTimeEnd);
                createdTimeEnd.start = laydate.now();
            })
        }
        outDate();


    function uploadImage(){
        //常规使用 - 普通图片上传
        var uploadInst = upload.render({
            elem: '#uploadImg'
            , url: webUrl+'/userinfo/uploadUserHeadImage'
            , before: function (obj) {
                //预读本地文件示例，不支持ie8
                obj.preview(function (index, file, result) {
                    $('#img_id').attr('src', result); //图片
                });
                element.progress('upload_filter', '0%'); //进度条
                layer.msg('上传中', { icon: 16, time: 0 });
            }
            , done: function (res) {
                if (res.errCode !== '000000') {
                    return layer.msg('上传失败');
                }
                $('#demoText').html(''); //置空上传失败的状态
                $("#ipt_fileName").val(res.msg);
                console.log(res)
                imageUrl = res.data;

            }
            , error: function () {
                //展示失败状态，并重新上传
                var demoText = $('#demoText');
                demoText.html('<span style="color: #ff5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                demoText.find('.demo-reload').on('click', function () {
                    uploadInst.upload();
                });
            }
            //进度条
            , progress: function (n, elem, e) {
                element.progress('upload_filter', n + '%'); //可配合 layui 进度条元素使用
                if (n == 100) {
                    layer.msg('上传完毕', { icon: 1 });
                }
            }
        });
        }
    });
</script>